import requests
import modules.host_packsges as hp
import datetime

# 获取商店id
def get_shop_id(connection):
    cookie_dict = hp.get_cookie_dict(connection, '米壳主体')
    # URL
    url = 'https://business.tiktok.com/api/v3/bm/account/list/'

    # Query Parameters (从 URL 中提取的参数)
    params = {
        'org_id': '7510229531278622721',
        'attr_source': 'TTAM_account_list',
        'source_biz_id': '',
        'attr_type': 'web',
        'account_type': '10',
        'page': '1',
        'limit': '100',
        'keyword': ''
    }

    # Headers
    headers = {
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'zh-CN,zh;q=0.9',
        'priority': 'u=1, i',
        'referer': 'https://business.tiktok.com/manage/accounts/tts?org_id=7510229531278622721&attr_source=TTAM_account_list&attr_type=web',
        'sec-ch-ua': '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
        'x-csrftoken': cookie_dict["csrftoken"]
    }

    # 发送 GET 请求
    response = requests.get(url, headers=headers, cookies=cookie_dict, params=params)
    # 获取响应内容
    data = response.json()["data"]["accounts"]
    id_name_list = [[row["account_id"],row["account_name"]] for row in data]
    print(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}  获取到{len(id_name_list)}个店铺信息")
    return id_name_list,cookie_dict

    # 输出响应内容
    # print(response.status_code)
    # print(response.json())
# 请求获取gmv数据
def get_gmv_data(connection,aadvid_name_list,zt_id,date_str):
    '''
    :param connection: 数据库连接对象
    :param aadvid_list: 广告组的id
    :param zt_id: 主体id
    :param date_str: 日期
    :return:
    '''
    data_list = []
    id_name_list,cookie_dict  = get_shop_id(connection)
    print(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}  准备开始逐个店铺、账户获取Gmv max数据......")
    for aadvid_name in aadvid_name_list:
        aadvid = aadvid_name[0]
        name = aadvid_name[1]
        for id_name in id_name_list:
            oec_seller_id = id_name[0]
            oec_seller_name = id_name[1]
            # 请求 URL
            url = "https://ads.tiktok.com/api/oec_shopping/v1/oec/stat/post_overview_stat"

            # Query 参数（URL 中的查询参数）
            params = {
                'locale': 'zh',
                'language': 'zh',
                'oec_seller_id': oec_seller_id,
                'aadvid': aadvid,
                'bc_id': zt_id
            }

            # Headers
            headers = {
                'accept': 'application/json, text/plain, */*',
                'accept-language': 'zh-CN,zh;q=0.9',
                'content-type': 'application/json; charset=UTF-8',
                'origin': 'https://ads.tiktok.com',
                'priority': 'u=1, i',
                'referer': f'https://ads.tiktok.com/i18n/gmv-max/dashboard?aadvid={aadvid}&oec_seller_id={oec_seller_id}&bc_id={zt_id}',
                'sec-ch-ua': '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
                'sec-ch-ua-mobile': '?0',
                'sec-ch-ua-platform': '"Windows"',
                'sec-fetch-dest': 'empty',
                'sec-fetch-mode': 'cors',
                'sec-fetch-site': 'same-origin',
                'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
                'x-csrftoken': cookie_dict["csrftoken"]
            }

            # 请求体数据（JSON 格式）
            data = {
                "query_list": ["cost", "onsite_roi2_shopping_sku", "cost_per_onsite_roi2_shopping_sku",
                               "onsite_roi2_shopping_value", "onsite_roi2_shopping"],
                "start_time": date_str,
                "end_time": date_str,
                "campaign_shop_automation_type": 2,
                "external_type_list": ["307", "304", "305"]
            }

            # 发送 POST 请求
            response = requests.post(url, params=params, headers=headers, cookies=cookie_dict, json=data)
            statistics_data = response.json()["data"]["statistics"]
            data_list.append({"账户名称":name,"账户ID":aadvid,"店铺名称":oec_seller_name,"店铺ID":oec_seller_id,"成本":statistics_data["cost"],"订单数":statistics_data["onsite_roi2_shopping_sku"],"平均下单成本":statistics_data["cost_per_onsite_roi2_shopping_sku"],"总收入":statistics_data["onsite_roi2_shopping_value"],"ROI":statistics_data["onsite_roi2_shopping"],"更新时间":datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')})
    print(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}  获取到{len(data_list)}条数据")
    return data_list